package com.beetobe.main;

//import static com.beetobe.main.CommonUtilities.SENDER_ID;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gcm.GCMBaseIntentService;

//�̰Ŵ� gcm���̺귯�� �������̵� onMessage�� �޽������� �����.
public class GCMIntentService extends GCMBaseIntentService {
	String c2dm_msg;
	static final String SENDER_ID = "656478210404";

	public GCMIntentService() {
		super(SENDER_ID);
	}

	private static final String TAG = "===GCMIntentService===";

	@Override
	protected void onRegistered(Context arg0, String registrationId) {
		Log.i(TAG, "Device registered: regId = " + registrationId);
	}

	@Override
	protected void onUnregistered(Context arg0, String arg1) {
		Log.i(TAG, "unregistered = " + arg1);
	}

	@Override
	protected void onMessage(Context arg0, Intent arg1) {
		Log.i(TAG, "CONTEXT :  = " + arg0);
		Log.i(TAG, "new message= ");

		if (arg1.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) {
			c2dm_msg = arg1.getExtras().getString("msg");
			GET_GCM();
		}
	}

	public void GET_GCM() {
		Thread thread = new Thread(new Runnable() {

			public void run() {
				handler.sendEmptyMessage(0);
			}
		});
		thread.start();

	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			Context context = getApplicationContext();
			int duration = Toast.LENGTH_LONG;
			Toast toast = Toast.makeText(context, c2dm_msg, duration);
			toast.show();
			Log.i(TAG, "Received c2dm_msg: " + c2dm_msg);

			
			
			// CalID + AccName

			String CalID = c2dm_msg.split("//")[0];
			String AccName = c2dm_msg.split("//")[1];

			Intent intent = new Intent(GCMIntentService.this, MainActivity.class);
			intent.putExtra("RECV_CAL_ID", CalID);
			intent.putExtra("RECV_ACCOUNT_NAME", AccName);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);



			startActivity(intent);
			
			
			

			c2dm_msg = null;
		}
	};

	@Override
	protected void onError(Context arg0, String errorId) {
		Log.i(TAG, "Received error: " + errorId);
	}

	@Override
	protected boolean onRecoverableError(Context context, String errorId) {
		return super.onRecoverableError(context, errorId);
	}

}
